package xyz.longicorn.driver.controller;

import cn.dev33.satoken.stp.StpUtil;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xyz.longicorn.driver.config.BizException;
import xyz.longicorn.driver.dto.ApiResult;
import xyz.longicorn.driver.dto.FastUploadFile;
import xyz.longicorn.driver.pojo.enums.Category;
import xyz.longicorn.driver.pojo.FileInfo;
import xyz.longicorn.driver.pojo.FolderInfo;
import xyz.longicorn.driver.service.FileService;
import xyz.longicorn.driver.service.FolderService;
import xyz.longicorn.driver.util.FileUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UploadController {
    private final static String SAVE_PATH = "D:\\tmp\\upload";
    private final static String ACCESS_PATH = "/upload";
    @Resource
    private FileService fileService;
    @Resource
    private FolderService folderService;

    private final static Map<String, String> FILE_MIME_TYPE = new HashMap<>();

    public UploadController() {
        FILE_MIME_TYPE.put("text/plain", "txt");
        FILE_MIME_TYPE.put("image/png", "png");
        FILE_MIME_TYPE.put("image/jpeg", "jpg");
        FILE_MIME_TYPE.put("image/jpg", "jpg");
        FILE_MIME_TYPE.put("image/bmp", "bmp");
        FILE_MIME_TYPE.put("image/webp", "webp");
        FILE_MIME_TYPE.put("image/gif", "gif");
        FILE_MIME_TYPE.put("image/svg+xml", "svg");
        FILE_MIME_TYPE.put("audio/mpeg", "mp3");
        FILE_MIME_TYPE.put("video/mp4", "mp4");
        FILE_MIME_TYPE.put("application/msword", "doc");
        FILE_MIME_TYPE.put("application/pdf", "pdf");
        FILE_MIME_TYPE.put("application/vnd.ms-excel", "xls");
        FILE_MIME_TYPE.put("application/vnd.ms-powerpoint", "ppt");
        FILE_MIME_TYPE.put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx");
        FILE_MIME_TYPE.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx");
        FILE_MIME_TYPE.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx");

    }

    @SneakyThrows
    @PostMapping("/upload")
    public ApiResult upload(@RequestParam("parent") String parent, @RequestPart("file") MultipartFile file) {
        Integer uid = StpUtil.getLoginIdAsInt();
        //
        // 1.计算md5
        String md5 = DigestUtils.md5DigestAsHex(file.getInputStream());
        FileInfo f = fileService.getByMd5(md5); //
        //
        FileInfo fileInfo = new FileInfo();
        if (parent.equals("/")) {
            fileInfo.setFolderId(0l);
        } else {
            FolderInfo folder = folderService.getByPath(uid, parent);
            if (folder == null) {
                throw BizException.create("保存目录不存在");
            }
            fileInfo.setFolderId(folder.getId());
        }
        fileInfo.setUid(uid);
        fileInfo.setHash(md5);//
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setSize(file.getSize());
        String type = getType(file.getContentType());// 获取文件的扩展名类型
        fileInfo.setType(type);

        if (FileUtils.isImage(type)) {
            fileInfo.setCategory(Category.Image);
        } else if (FileUtils.isDocument(type)) {
            fileInfo.setCategory(Category.Document);
        } else if (FileUtils.isVideo(type)) {
            fileInfo.setCategory(Category.Video);
        } else if (FileUtils.isAudio(type)) {
            fileInfo.setCategory(Category.Audio);
        } else {
            fileInfo.setCategory(Category.Other);
        }


        if (f != null) { // 系统已经存在了该文件
            // 不保存上传文件 直接copy数据
            fileInfo.setPath(f.getPath());
        } else {
            String path = SAVE_PATH + "\\" + md5;//文件的保存路径
            fileInfo.setPath(path);
            // 爆保存上传文件
            file.transferTo(new File(path));
        }
        fileService.save(fileInfo);//保存文件信息
        return ApiResult.success(null);
    }

    // 将mimetype -> 文件后缀名的类型
    private String getType(String mimeType) {
        String type = mimeType.toLowerCase();
        if (FILE_MIME_TYPE.containsKey(type)) {
            return FILE_MIME_TYPE.get(type);
        }
        return "file";
    }

    @PostMapping("/fast-upload")
    public ApiResult fastUpload(@RequestBody FastUploadFile file) {
        int uid = 1;

        file.setType(getType(file.getType()));

        FileInfo info = fileService.fastUpload(uid, file);
        return ApiResult.success(info);
    }
}
